package com.sansan.qiangji.controller.device;

import com.sansan.qiangji.VO.device.BeltVO;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.device.belt.BeltAddForm;
import com.sansan.qiangji.form.device.belt.BeltEditForm;
import com.sansan.qiangji.realize.device.BeltReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@CrossOrigin()
@RestController
@RequestMapping("/belt")
@Slf4j
public class BeltController {
    private BeltReal beltReal;

    @Resource
    public void setBeltReal(BeltReal beltReal){
        this.beltReal = beltReal;
    }

    @GetMapping("/list")
    public ResultVO<Object> beltList() {
        List<BeltVO> beltVOS = beltReal.beltList();
        return ResultVOUtil.success(beltVOS);
    }

    @PostMapping("/create")
    public ResultVO<Object> beltCreate(@Valid @RequestBody BeltAddForm beltAddForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【添加传送带】参数不正确，beltAddForm={}", beltAddForm.toString());
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        beltReal.beltCreate(beltAddForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/edit")
    public ResultVO<Object> beltEdit(@Valid @RequestBody BeltEditForm beltEditForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【编辑传送带】参数不正确，beltEditForm={}", beltEditForm.toString());
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        beltReal.beltEdit(beltEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/delete")
    public ResultVO<Object> deleteBelt(@RequestParam(name = "beltId") Integer beltId) {
        beltReal.deleteBelt(beltId);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/getBeltParamDetail")
    public ResultVO<Object> getBeltParamDetail(@RequestParam(name = "beltId") Integer beltId) {
        return ResultVOUtil.success(beltReal.getBeltParamDetail(beltId));
    }
}
